﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kooboo.Commerce.AddIn;
using System.ComponentModel.Composition;
using Kooboo.Commerce.Promotions.CouponCode.Models;

namespace Kooboo.Commerce.Promotions.CouponCode
{
    [Export(typeof(IPromotion))]
    public class CouponCodePromotion : IPromotion
    {
        public string Name
        {
            get { return "DiscountByCouponCode"; }
        }

        public string HeadLine
        {
            get { return "DiscountByCouponCode"; }
        }

        public IPromotionViews Views
        {
            get { return new CouponCodeView(); }
        }

        public bool Execute(IPromotionRule rule, Connect.User user, PromotionContext context)
        {
            var settings = Services.Current.Find(rule);
            if (settings != null && !String.IsNullOrEmpty(context.CouponCode))
            {
                if (String.Compare(context.CouponCode, settings.GouponCode) == 0)
                {
                    if (settings.ReduceType == (int)ReduceType.ByFee)
                    {
                        context.Discount += settings.ReduceValue;
                        context.Total -= settings.ReduceValue;
                    }
                    else
                    {
                        var discount = context.Total * settings.ReduceValue;
                        context.Discount += discount;
                        context.Total -= discount;
                    }

                    return true;
                }
            }

            return false;
        }

        public void RemoveSettings(IPromotionRule rule, Connect.User user)
        {
            Services.Current.Remove(rule);
        }
    }
}